package com.bbcare.cp.plat.service.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtil;
import com.bbcare.cp.plat.entity.au.AuDoctor;
import com.bbcare.cp.plat.entity.cp.IaOperationRecord;
import com.bbcare.cp.plat.service.IDocManageService;
import com.bbcare.cp.plat.service.IOprRecordService;
import com.bbcare.cp.plat.store.ibatis.au.IAuDoctorDAO;
/**
 * @name: 医生列表
 * @author: DemonLee
 * @createTime: 2018.5.6
 */
@Service
public class DocManageServiceImpl implements IDocManageService {
    private final Log logger = LogFactory.getLog(DocManageServiceImpl.class);

    @Autowired
    private IAuDoctorDAO auDoctorDao;

    @Autowired
    private IOprRecordService oprRecordService;
    /**
     * 查询医生列表
    * @author fangxm
    * @date 2018年5月31日
     */
	@Override
	public Map<String, Object> qryDoctorList(Map<String, Object> argMap) throws Exception {
		logger.debug("---qryDoctorList---argMap==" + argMap);
		Map<String, Object> outMap = new HashMap<String, Object>();
		List<AuDoctor> list = new ArrayList<>();
		int count=auDoctorDao.qryDoctorListCnt(argMap);
		if(count>0){
			list=auDoctorDao.qryDoctorList(argMap);
			if(CollectionUtils.isEmpty(list)){
				count=0;
			}
		}
		outMap.put("total", count);
		outMap.put("rows", list);
		return outMap;
	}

	//新增医生列表
	@Override
	@Transactional
	public Map<String, Object> addDoctor(Map<String, Object> argMap) throws Exception {
		Map<String, Object> outMap = new HashMap<String, Object>();
		Map<String, Object> docMap = new HashMap<String, Object>();
		Map<String, Object> sessionInfo = ToolUtil.typeCast(argMap.get("sessionInfo"));
		String authorId = (String) sessionInfo.get("authorId");
		String updateTime = DateUtil.getSysDateA();
		String doctorId = (String) argMap.get("id");
		String flag = (String) argMap.get("flag");
		docMap.put("id", doctorId);
		docMap.put("userName", argMap.get("userName"));
		docMap.put("gender", argMap.get("gender"));
		docMap.put("title", argMap.get("title"));
		docMap.put("phoneNo", argMap.get("phoneNo"));
		docMap.put("address", argMap.get("address"));
		docMap.put("createTime", updateTime);
		docMap.put("createAuthor", authorId);
		docMap.put("updateTime", updateTime);
		docMap.put("updateAuthor", authorId);
		docMap.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
		if (Constants.HANDLE_TYPE_ADD.equals(flag)) {
			docMap.put("id", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_DOCTOR_HOS_ID));//医生医院关联表的主键ID
			doctorId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_DOCTOR_ID);// 医生id
			docMap.put("doctorId", doctorId);
			auDoctorDao.addDoctoInfo(docMap);
			auDoctorDao.addDoctoHosRole(docMap);
		} else {
			if (StringUtils.isEmpty(doctorId)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "医生编码不能为空"));
			}
			docMap.put("id", doctorId);
			auDoctorDao.modifyDoctoInfo(docMap);
		}
		argMap.put("id", doctorId);
		this.saveOprRecordInfo(argMap);
		outMap.put("id", doctorId);
		return outMap;
	}
	/*日志操作记录表*/
	public void saveOprRecordInfo(Map<String, Object> mapIn) throws Exception {
		Map<String, Object> sessionInfo = ToolUtil.typeCast(mapIn.get("sessionInfo"));
		Map<String, Object> oprInfo = ToolUtil.typeCast(mapIn.get(Constants.INF_INPUTPARAM_OPRINFO_FIELD));
		String opType = (String) oprInfo.get("opType");
		String channelId = (String) oprInfo.get("channelId");
		String channelType = (String) oprInfo.get("channelType");
		String opCode = (String) oprInfo.get("opCode");
		String opNote = (String) oprInfo.get("opNote");
		String updateAccept = (String) oprInfo.get("updateAccept");
		String updateTime = (String) oprInfo.get("updateTime");
		String authorId = (String) sessionInfo.get("authorId");
		String projectRoleId = (String) sessionInfo.get("projectRoleId");
		String tenantId = (String) sessionInfo.get("tenantId");
		String id = (String) mapIn.get("id");
		// 入操作流水记录表 ia_operation_record
		Calendar now = Calendar.getInstance();
		String month = String.valueOf(now.get(Calendar.MONTH) + 1);
		String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
		IaOperationRecord OperationRecord = new IaOperationRecord();
		OperationRecord.setBusiCategory(null);
		OperationRecord.setBusiId(id);
		OperationRecord.setChannelId(channelId);
		OperationRecord.setChannelType(channelType);
		OperationRecord.setDay(day);
		OperationRecord.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
		OperationRecord.setMonth(month);
		OperationRecord.setOpCode(opCode);
		OperationRecord.setOpDesc(opNote);
		OperationRecord.setOpTime(updateTime);
		OperationRecord.setOpType(opType);
		OperationRecord.setOpUser(authorId);
		if (Constants.OP_TYPE_SELF.equals(opType)) {
			OperationRecord.setOpUsertype(Constants.OPCODE_TYPE_PATIENT);
		} else {
			OperationRecord.setOpUsertype(Constants.OPCODE_TYPE_DOCTOR);
		}
		OperationRecord.setProjectRoleId(projectRoleId);
		OperationRecord.setQueueId(null);
		OperationRecord.setRemark(null);
		OperationRecord.setTaskId(null);
		OperationRecord.setTenantId(tenantId);
		OperationRecord.setUpdateAccept(updateAccept);
		OperationRecord.setUserId(id);
		Map<String, Object> saveMapIn = new HashMap<String, Object>();
		saveMapIn.put("OperationRecord", OperationRecord);
		oprRecordService.saveOprRecordService(saveMapIn);// 日志记录
	}

	/*查询医生职称下拉*/
	@Override
	public Map<String, Object> qryDoctorTitleList(Map<String, Object> argMap) throws Exception {
		List<String> list=new ArrayList<>();
		Map<String, Object> outMap=new HashMap<>();
		list.add("初级职称（医士、医师、住院医师）");
		list.add("中级职称（主冶医师）");
		list.add("副高级职称（副主任医师）");
		list.add("高级职称（主任医师）");
		//list=auDoctorDao.qryDoctorTitleList(argMap);
		outMap.put("rows", list);
		return outMap;
	}

	/*查询排班列表*/
	@Override
	public Map<String, Object> qryPatientRecordList(Map<String, Object> argMap) throws Exception {
		Map<String, Object> outRet = new HashMap<String, Object>();
		Map<String, Object> qryMap = new HashMap<String, Object>();
		List<Map<String, Object>> ropsList = new ArrayList<Map<String, Object>>();
		int groupType = (Integer) argMap.get("groupType");
		String rootGroupId = (String) argMap.get("rootGroupId");
		String tenantId = (String) argMap.get("tenantId");
		qryMap.put("groupType", groupType);
		qryMap.put("deptId", rootGroupId);
		qryMap.put("tenantId", tenantId);
		// 目前根据租户-去排班  其他情况暂时不考虑
		//qryMap.put("deptId", rootGroupId);
		ropsList = auDoctorDao.listRandOutPatientScheduleByDept(qryMap);
		outRet.put("rows", ropsList);
		return outRet;
	}

	/*删除排班*/
	@Override
	@Transactional
	public Map<String, Object> removeRandOutPatient(Map<String, Object> argMap) throws Exception {
		Map<String, Object> outMap = new HashMap<String, Object>();
		Map<String, Object> qryMap = new HashMap<String, Object>();
		String scheduleId = (String) argMap.get("scheduleId");
		qryMap.put("id", scheduleId);
        auDoctorDao.deleteRandOutPatientSchedule(qryMap);
		/*操作日志表*/
        argMap.put("id", scheduleId);
		this.saveOprRecordInfo(argMap);
		outMap.put("id", scheduleId);
		return outMap;
	}

	/*新增排班*/
	@Override
	@Transactional
	public Map<String, Object> saveRandOutPatient(Map<String, Object> argMap) throws Exception {
		Map<String, Object> outMap = new HashMap<String, Object>();
		Map<String, Object> inMap = new HashMap<String, Object>();
		Map<String, Object> oprInfo = ToolUtil.typeCast(argMap.get(Constants.INF_INPUTPARAM_OPRINFO_FIELD));
		int groupType = (Integer) argMap.get("groupType");
		String rootGroupId = (String) argMap.get("rootGroupId");
		String tenantId = (String) argMap.get("tenantId");
		inMap.put("groupType", groupType);
		inMap.put("tenantId", tenantId);
	    String opTime = DateUtil.getSysDateA();
		// 排班业务信息
        inMap.put("workDay",  argMap.get("workDay"));
        inMap.put("workPeriod",  argMap.get("workPeriod"));
        inMap.put("deptId", rootGroupId);
        inMap.put("scheduleType",  argMap.get("scheduleType"));
        inMap.put("createTime", opTime);
        inMap.put("updateTime", opTime);
        inMap.put("createAuthor", argMap.get("authorId"));
        inMap.put("updateAccept",  oprInfo.get("updateAccept"));
        String scheduleId = "";
        // 租户排班
        scheduleId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_OUTPATIENT_SCHEDULE);
        inMap.put("id", scheduleId);
        int chkNum = auDoctorDao.countRandOutPatientScheduleByUnique(inMap);
        if (chkNum > 0) {
            // 已添加，无法重复添加
            throw (new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DUPLICATE_OUTPATIENT_SCHEDULE, "该工作日时段排班已设置，无法重复设置!"));
        }
        auDoctorDao.saveRandOutPatientSchedule(inMap);
		/*操作日志表*/
        argMap.put("id", scheduleId);
		this.saveOprRecordInfo(argMap);
		outMap.put("id", scheduleId);
		return outMap;
	}


}
